package com.ruoyi.lowcode.utils;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.lowcode.config.OpenApiConfig;
import com.ruoyi.lowcode.domain.vo.ModelInfoVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@Slf4j
@Component
public class WordUtils {

    @Resource
    private OpenApiConfig openApiConfig;

    private static Configuration configuration = null;
    private static final String templateFolder = WordUtils.class.getResource("/ftl").getPath();

    static {
        configuration = new Configuration(new Version("2.3.32"));
        configuration.setDefaultEncoding("UTF-8");
        try {
            configuration.setDirectoryForTemplateLoading(new File(templateFolder));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void exportOpenApiWord(ModelInfoVo modelInfo, HttpServletResponse response) throws IOException {
        Template freemarkerTemplate = configuration.getTemplate(openApiConfig.getFtlName(), "UTF-8");
        Writer out = null;
        InputStream fis = null;
        try {
            // 生成word路径
            String docFilePath = openApiConfig.getGenerateFilePath() + modelInfo.getModel().getModelName() + System.currentTimeMillis() + ".doc";
            // 文件
            File file = new File(docFilePath);

            // 创建一个Word文档的输出流
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            //FreeMarker使用Word模板和数据生成Word文档
            freemarkerTemplate.process(modelInfo, out);
            out.flush();

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=");
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
        }catch (Exception e){
            e.printStackTrace();
            log.error("下载接口文档出错，原因" + e.getMessage());
        }finally {
            if(ObjectUtil.isNotNull(out)){
                out.close();
            }
            if(ObjectUtil.isNotNull(fis)){
                fis.close();
            }
        }
    }

}
